package net.sureon.web.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.app.UserSession;
import net.sureon.biz.UserBO;
import net.sureon.biz.UserMgr;
import net.sureon.common.security.SecurityUtils;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class ChangePassword implements Controller {

	private UserMgr userMgr;
	private UserBO user;

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		long userID = ((net.sureon.app.UserSession) request.getSession()
				.getAttribute(UserSession.HTTP_SESSION_KEY)).getUserID();

		long companyID = ((net.sureon.app.UserSession) request.getSession()
				.getAttribute(UserSession.HTTP_SESSION_KEY)).getCompanyID();
		
		String isFirstGo = request.getParameter("isFirstGo");
		
		if("yes".equals(isFirstGo)) {
		

			user = userMgr.getUser(companyID, userID);
			
			// 获取表单填写的密码
			String inputPassword = request.getParameter("currentPwd");
			// 判断和数据库中是否一致
			boolean isVerify = false;
			isVerify = user.verifyPassword(inputPassword);
			if(isVerify) {
				// 密码正确，修改密码
				String encPassword = SecurityUtils.generateSHA512Hash(user.getUserVO().getSalt() + ":" + request.getParameter("newPwd"));
				
				user.getUserVO().setPassword(encPassword);
				
				int rows = userMgr.updateUser(user);
				if(rows > 0 ){
					// 更新成功
					request.setAttribute("successMsg", "恭喜你，密码更新成功！");
				} else {
					request.setAttribute("successMsg", "程序出错，修改密码失败，请重新修改");
				}
				
			} else {
				// 密码不正确
				request.setAttribute("errorMsg", "当前密码输入不正确！");
			}
		}
		
		return new ModelAndView("user/changePassword");
	}

	public UserMgr getUserMgr() {
		return userMgr;
	}

	public void setUserMgr(UserMgr userMgr) {
		this.userMgr = userMgr;
	}
}
